/*
Copyright (C) 2022-2024 Inspur Corp.

SPDX-License-Identifier: Apache-2.0
*/
package service

import (
	"github.com/pkg/errors"
	"icep/bean/entity"
	"icep/bean/model"
	"icep/common/file"
	"icep/common/upload"
	"icep/common/utils"
	"icep/common/uuid"
	"mime/multipart"
	"os"
	"time"
)

func (is *IcepService) GetRealNameOrg(userId string) (*model.RealNameOrgDetail, error) {
	org := make([]*entity.IcepRealNameOrg, 0)
	orgErr := is.DbEngine.Where("user_id = ? and status = '1'", userId).Find(&org)
	if orgErr != nil {
		return nil, orgErr
	}
	if len(org) == 0 {
		return nil, errors.New("企业实名认证信息为空!")
	}
	user := make([]*entity.IcepUser, 0)
	userErr := is.DbEngine.Where("id = ? and status = '1'", userId).Find(&user)
	if userErr != nil {
		return nil, userErr
	}
	if len(user) == 0 {
		return nil, errors.New("用户信息为空!")
	}
	tenant := make([]*entity.IcepTenantIdentity, 0)
	tenantErr := is.DbEngine.Where("tenant_id = ? ", user[0].TenantId).Find(&tenant)
	if tenantErr != nil {
		return nil, tenantErr
	}
	if len(tenant) == 0 {
		return nil, errors.New("租户身份信息为空!")
	}
	orgDetail := &model.RealNameOrgDetail{
		OrgName:         org[0].OrgName,
		OrgCode:         org[0].OrgCode,
		LegalPersonName: org[0].LegalPerson,
		LegalPersonId:   org[0].PersonId,
		OrgLicense:      org[0].OrgLicense,
		IdCardFront:     org[0].IdCardFront,
		IdCardBack:      org[0].IdCardBack,
		Status:          org[0].Status,
		UserPubKey:      user[0].PubKey,
		ChainPubKey:     tenant[0].PubKey,
		ChainCert:       tenant[0].Cert,
	}

	return orgDetail, nil
}

func (is *IcepService) CreateRealNameOrg(userId string, orgName string, orgCode string, legalPersonName string,
	legalPersonId string, orgLicense *multipart.FileHeader, idCardFront *multipart.FileHeader, idCardBack *multipart.FileHeader) error {
	org := make([]entity.IcepRealNameOrg, 0)
	err := is.DbEngine.Where("user_id = ? and status != '2'", userId).Find(&org)
	if err != nil {
		return errors.Errorf("query org error: %s", err)
	}
	if len(org) > 0 {
		return errors.New("已存在实名认证流程，请勿重复发起！")
	}

	id := uuid.Generate()
	orgLicenses := orgCommon(orgLicense, id)
	idCardFronts := orgCommon(idCardFront, id)
	idCardBacks := orgCommon(idCardBack, id)
	orgEntity := entity.IcepRealNameOrg{
		Id:          id,
		UserId:      userId,
		OrgName:     orgName,
		OrgCode:     orgCode,
		LegalPerson: legalPersonName,
		PersonId:    legalPersonId,
		OrgLicense:  orgLicenses,
		IdCardFront: idCardFronts,
		IdCardBack:  idCardBacks,
		Status:      "1",
		CreatedTime: time.Now(),
		UpdatedTime: time.Now(),
	}
	_, err = is.DbEngine.InsertOne(orgEntity)
	if err != nil {
		return errors.Errorf("insert org error: %s", err)
	}
	return nil

}

func orgCommon(files *multipart.FileHeader, id string) string {
	filename := files.Filename
	tempDir := os.TempDir()
	path := utils.StrJoin(tempDir, "/", id, "/")
	client := upload.GetUploadClient()
	newPath := path + filename
	file.CreateIfNotExists(newPath, false)
	err := file.SaveUploadedFile(files, newPath)
	if err != nil {
		log.Errorf("save uploaded file error: %s", err)
	}
	url, err := client.UploadFile(path+filename, id+"/"+filename)
	errs := file.DeleteFileAll(path)
	if errs != nil {
		log.Errorf("删除本地文件失败: %s", errs)
	}
	return url

}
